// 上传文件封装
export const upload = function (Vue, options) {
  Vue.prototype.$upload = {
    uploadAction: function (options) {
      if (!this.UtilType.isJSON(options)) {
        console.log('upload options is null');
        return;
      }
      // 上传路径不能为空
      if (!options.url) {
        console.log('upload url is null');
        return;
      }
      // 上传文件不能为空
      if (!options.file) {
        console.log('upload file is null');
        return;
      }
      let _options = {file: options.file, url: options.url};
      _options.success = this.UtilType.isFunction(options.success) ? options.success : function () {};
      _options.fail = this.UtilType.isFunction(options.fail) ? options.fail : function () {};
      _options.progress = this.UtilType.isFunction(options.progress) ? options.progress : function () {};
      this.uploadEvent(_options);
    },
    UtilType: {
      isPrototype: function (data) {
        return Object.prototype.toString.call(data).toLowerCase();
      },
      isJSON: function (data) {
        return this.isPrototype(data) === '[object object]';
      },
      isFunction: function (data) {
        return this.isPrototype(data) === '[object function]';
      }
    },
    uploadEvent: function (options) {
      let formData = new FormData();
      formData.append('files', options.file);
      this.requestEvent({
        formData,
        success: options.success,
        fail: options.fail,
        progress: options.progress,
        url: options.url
      });
      // let input = document.createElement('input')
      // input.setAttribute('type', 'file')
      // input.setAttribute('name', 'files')
      // input.click()
      // input.onchange = function () {
      //   file = input.files[0];
      // }
    },
    requestEvent: function (options) {
      try {
        let formData = options.formData;
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            options.success(JSON.parse(xhr.responseText));
          }
        };
        xhr.upload.onprogress = function (evt) {
          let loaded = evt.loaded;
          let tot = evt.total;
          // let per = Math.floor(loaded / tot);
          options.progress({loaded: loaded, total: tot});
        };
        xhr.open('post', options.url);
        xhr.send(formData);
      } catch (err) {
        options.fail(err);
      }
    }
  };
};
